package com.smartlbs.socket;

import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.smartlbs.baseframe.web.InitTask;
import com.smartlbs.service.IUserBasicService;

//
@ServerEndpoint("/websocket")
public class SocketServer {
	//
	private static Logger logger = Logger.getLogger(SocketServer.class);
	
	private IUserBasicService userBasicService;
	
	private SocketServer() {
		//
		userBasicService = (IUserBasicService)InitTask.getSpringBean("userBasicService");
	}
	
	//存放session对象
	private static ConcurrentHashMap<Long, Session> sessionMap = new ConcurrentHashMap<Long, Session>();

	public static ConcurrentHashMap<Long, Session> getSessionMap(){
		return sessionMap;
	}
	
	/**
	 * 连接建立成功调用的方法
	 * 
	 * 
	 * @param session  可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
	 */
	@OnOpen
	public void onOpen(Session session){
		logger.info("有新用户进入,SessionID为====="+session.getId());
	}

	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param message 客户端发送过来的消息
	 * @param session 可选的参数
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		//
		logger.info("来自客户端的消息:" + message);
		//
		SendModel sendModel = JSON.parseObject(message, SendModel.class);
		//
		int resourceType = sendModel.getResourceType();
		long userId = sendModel.getUserId();
		//
		switch(resourceType){
			case 1://用户注册
				registerUser(userId, session);
				break;
			default:
				break;
		}
	}
	
	//用户注册
	private void registerUser(Long userId, Session session){
		try {
			//
			sessionMap.put(userId, session);
			
			userBasicService.updateSessionId(userId, session.getId());
			//
//			Session useSession = sessionMap.get(roomUser.getUser_id());
//			//
//			if(useSession != null && useSession.isOpen()){
//				//
//				useSession.getBasicRemote().sendText(JSON.toJSONString(sendModel));
//			}
			//
			logger.info("用户注册成功");
		} catch (Exception e) {
			//
			logger.error("用户注册websocket失败");
			e.printStackTrace();
		}
	}
}
